<?php
require 'searchBook_Class.php';
/**数据采集工厂
 * @author zhutl
 *
 */
class searchFactory {
	public $keywords = '';
	public $db;	//数据库对象
	public $mc;
	public $page = 1;
	public $type = 'pdf';
	public $returnCount = 10;//返回的数据数量
	public $cachetime = 86400;
	public $search_urls = array();
	public function __construct($db, $mc, $keywords = "", $search_urls = array()) {
		$this -> db = $db;
		$this -> mc = $mc;
		$this -> keywords = $keywords;
		$this -> search_urls = $search_urls;
	}

	public function set_keywords($keywords) {
		$this -> keywords = $keywords;
		return $this;
	}

	public function set_type($type) {
		$this -> type = $type;
		return $this;
	}

	public function set_page($page) {
		$this -> page = $page;
		return $this;
	}

	public function set_cachetime($cachetime) {
		$this -> cachetime = $cachetime;
		return $this;
	}

	public function set_returnCount($returnCount) {
		$this -> returnCount = $returnCount;
		return $this;
	}

	public function start($star = 1, $pn = 1) {

		$key = "'" . md5($this -> keywords . $star . $pn) . "'";

		if ($pn == 1) {

			$key = "'" . md5($this -> keywords . "11") . "'";
			//echo $key;

		}
		// echo $key;

		if ($this -> have_cached($key) == 'true') {

			//echo 'cache<br/>';
			return $this -> mc -> get($key);
		}

		return $this -> have_searched($this -> cachetime, $star, $pn);
	}

	public function get_star($kid) {

		$table = "bs_result" . $kid % 16;

		$sql = "SELECT count(*) as count
			FROM  `$table`
			WHERE  `kid` =  '$kid'	
			and source =2
			
			";

		//echo $sql;
		$rows = $this -> db -> find($sql);

		//print_r($rows);exit;
		return $rows[0] -> count;

	}
	public static function get_keywords($db){
	 
		$sql = "SELECT keyword
			FROM  `bs_keywords`			
			ORDER BY kid desc			
			";
			$rows = $db -> find($sql);
			
			return $rows;
		
		
		
	}
	private function select($kid, $start = 1, $pn = 1) {
		$table = "bs_result" . $kid % 16;
		if (1 == $pn) {

			$sql = "SELECT *
			FROM  `$table`
			WHERE  `kid` =  '$kid'	
			and source =2
			ORDER BY rid ASC			
			";
			$rows = $this -> db -> find($sql);
			return $rows;
		}
		$star = $start + ($pn - 2) * $this -> returnCount;
		$sql = "SELECT *
		FROM  `$table`
		WHERE  `kid` =  '$kid'		
		ORDER BY rid ASC
		LIMIT $star,$this->returnCount
		";
		$rows = $this -> db -> find($sql);
		return $rows;

	}

	public function check_frist() {

		$key = "'" . md5($this -> keywords) . "'";
		//echo $this->have_cached($key);
		//echo $this->check_mysql();

		if ($this -> check_mysql() == 'false') {

			return false;
		}

		return true;

	}

	public function get_kid() {

		$keywords = mysql_escape_string($this -> keywords);
		$sql = "SELECT kid
		FROM  `bs_keywords`
		WHERE  `keyword` =  '$keywords'		
		ORDER BY kid 
		LIMIT 1		
		";
		//echo $sql;exit;
		$rows = $this -> db -> find($sql);
		return $rows[0] -> kid;

	}

	/**有数据返回true 没有返回false
	 * @return bollen
	 */
	public function check_mysql() {

		$keywords = mysql_escape_string($this -> keywords);
		$sql = "SELECT kid,updatetime
		FROM  `bs_keywords`
		WHERE  `keyword` =  '$keywords'		
		ORDER BY kid 
		LIMIT 1		
		";
		//echo $sql;exit;
		$rows = $this -> db -> find($sql);
		if (!$rows) {
			return 0;
		}
		//print_r($rows);
		//echo $rows[0]->updatetime;
		if ((time() - $rows[0] -> updatetime) > $this -> cachetime) {

			$DayStartTime = mktime(0, 0, 0, date('m', time()), date('j', time()), date('Y', time()));
			$newdata = array('updatetime' => $DayStartTime, );

			$this -> db -> update('bs_keywords', $newdata, $rows[0] -> kid, $field = 'kid');
			$this -> del_old($rows[0] -> kid);
			return "gengxin";

		}

		return $rows[0] -> kid;

	}

	/**有数据返回true 没有返回false
	 * @param unknown_type $key
	 * @return bollen
	 */
	private function have_cached($key) {

		if (!$this -> mc -> get($key)) {
			//echo aa;
			return 'false';
			//没有缓存

		}
		return 'true';
	}

	/**查询是否在time时间内查询过数据库
	 * @param time $time
	 * @retrun bollean
	 */
	private function have_searched($time, $star = 1, $pn = 1) {

		$DayStartTime = mktime(0, 0, 0, date('m', time()), date('j', time()), date('Y', time()));
		//$time=time()-$time;
		$keywords = mysql_escape_string($this -> keywords);
		$key = "'" . md5($this -> keywords . $star . $pn) . "'";

		$sql = "SELECT kid,updatetime
		FROM  `bs_keywords`
		WHERE  `keyword` =  '$keywords'		
		ORDER BY kid 
		LIMIT 1		
		";
		$rows = $this -> db -> find($sql);
		//echo $rows[0]->updatetime;

		//echo 'mysql';
		//echo $pn;
		if (1 == $pn) {

			$key = "'" . md5($this -> keywords . "11") . "'";

		}
		$data = $this -> select($rows[0] -> kid, $star, $pn);

		$this -> add_cached($key, $data);

		return $data;

	}

	private function del_old($kid) {

		$table = "bs_result" . $kid % 16;
		$this -> db -> remove($table, $kid, 'kid');

	}
	public function del_null_size($kid,$rid) {

		$table = "bs_result" . $kid % 16;
		$this -> db -> remove($table, $rid, 'rid');
		
	}
	/**把查询多数据插入数据库
	 *
	 */
	public function save_frist_result($update) {

		//$time=time();
		$DayStartTime = mktime(0, 0, 0, date('m', time()), date('j', time()), date('Y', time()));
		$keywords = mysql_escape_string($this -> keywords);
		$key = "'" . md5($this -> keywords . '11') . "'";

		if ($update == "0") {
			$rows = array('keyword' => $keywords, 'updatetime' => $DayStartTime, 'hits' => 1, );
			$this -> db -> save('bs_keywords', $rows);
			$kid = $rows['id'];
		}
		if ($update == "gengxin") {
			//echo aaa;exit;
			$sql = "SELECT kid,updatetime
		FROM  `bs_keywords`
		WHERE  `keyword` =  '$keywords'		
		ORDER BY kid 
		LIMIT 1		
		";
			$rows = $this -> db -> find($sql);
			$kid = $rows[0] -> kid;

		}
		$table = "bs_result" . $kid % 16;
		$mp = new SearchBook($this -> keywords);
		$data = $mp -> getFristDate($this -> keywords);
		if (!empty($data)) {
			foreach ($data as $p) {
				$p['kid'] = $kid;
				$p['title'] = mysql_escape_string(urldecode($p['title']));
				$p['remarks'] = mysql_escape_string($p['remarks']);
				$this -> db -> save($table, $p);

			}

			$results = $this -> select($kid);

			$this -> add_cached($key, $results);

			return $results;
		}

	}

	/**把查询多数据插入数据库
	 *
	 */
	public function save_result($kid, $star) {
		$time = time();
		$key = "'" . md5($this -> keywords . $star) . "'";
		$keywords = mysql_escape_string($this -> keywords);
		//print_r($kid);exit;
		$table = "bs_result" . $kid % 16;
		$this -> real_urls();
		//print_r($this->search_urls);exit;
		$mp = new SearchBook($this -> keywords, $this -> search_urls);
		$mp -> set_page($this -> page);
		$data = $mp -> getDate();
		if (!empty($data)) {
			//$data=array_reverse($data);
			//print_r($data);
			foreach ($data as $p) {
				$p['kid'] = $kid;
				$p['title'] = mysql_escape_string(urldecode($p['title']));
				$p['remarks'] = mysql_escape_string($p['remarks']);
				$this -> db -> save($table, $p);

			}
			//exit;
			$results = $this -> select($kid);
			$this -> add_cached($key, $results);
			//print_r($results);exit;
			return $results;
		}
	}

	private function real_urls() {

		//print_r($this->search_urls);
		foreach ($this->search_urls as $k => $p) {

			if ($p['state'] == 0) {
				unset($this -> search_urls[$k]);
			}
		}
		sort($this -> search_urls);

	}

	/**添加记录到缓存
	 * @param unknown_type $key
	 * @param unknown_type $date
	 */
	public function add_cached($key, $date) {
		if ($this -> mc -> add($key, $date, false, $this -> cachetime)) {
			return true;
		}
		return false;
	}

	/**创建子表
	 * @param unknown_type $table
	 */
	private function create_table($table) {

		$sql = "SELECT count(*)
		FROM  `$table`";

		$havetable = $this->db -> find($sql);

		if (!$havetable) {
			$sql = "CREATE TABLE IF NOT EXISTS `$table`
			(
			`rid` mediumint(9) NOT NULL AUTO_INCREMENT,
			`title` varchar(100) NOT NULL,
			`url` varchar(200) NOT NULL,
			`remarks` varchar(500) NOT NULL,
			`kid` mediumint(9) NOT NULL,
			PRIMARY KEY (`rid`)
			)";
			$this -> db -> query($sql);
		}

	}

	/**获取远程文件大小
	 * @param unknown_type $url
	 * @return string|NULL
	 */
	public static function getFileSize($url) {
		$url = parse_url($url);
		if ($fp = @fsockopen($url['host'], empty($url['port']) ? 80 : $url['port'], $error)) {
			fputs($fp, "GET " . (empty($url['path']) ? '/' : $url['path']) . " HTTP/1.1\r\n");
			fputs($fp, "Host:$url[host]\r\n\r\n");
			while (!feof($fp)) {
				$tmp = fgets($fp);
				if (trim($tmp) == '') {
					break;
				} else if (preg_match('/Content-Length:(.*)/si', $tmp, $arr)) {
					return trim($arr[1]);
				}
			}
			return null;
		} else {
			return null;
		}
	}
	public static function sizecount($filesize) {
		if ($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
		} elseif ($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
		} elseif ($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		}
		return $filesize . 'B';

	}

	public function get_size_from_mysql($db, $kid, $rid) {
		$table = "bs_result" . $kid % 16;
		$sql = "SELECT size
		FROM  `$table`
		WHERE  `rid` =  '$rid'				
		LIMIT 1		
		";
		//echo $sql;exit;
		$rows = $db -> find($sql);

		if ($rows[0] -> size != null) {

			$key = "'" . md5($table . $rid) . "'";
			$this -> add_cached($key, $rows[0] -> size);
		}

		return $rows[0] -> size;

	}

	public static function save_size($db, $kid, $rid, $size) {
		$table = "bs_result" . $kid % 16;
		$newdata = array('size' => $size);

		$db -> update($table, $newdata, $rid, $field = 'rid');

		//return $rows[0]->size;

	}

}
?>